package com.locatme.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.locatme.adapter.MessageViewAdapter;
import com.locatme.model.Enseigne;
import com.locatme.model.Message;
import com.locatme.model.Personne;
import com.locatme.model.Utilisateur;
import com.locatme.modelBD.MessageBD;
import com.locatme.modelBD.UtilisateurBD;
import com.main.locatme.JSONParser;
import com.main.locatme.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class SendMessageFragment extends Fragment {

    private String txtemetteur;
    private EditText editdestin;

    private EditText editmessage;
    private MessageBD messageBD;
    private MessageBD messageBDList;
    private Message msg;
    private List<Message> messages, messages2;
    private MessageViewAdapter adapter;

    private Bundle args;
    private Utilisateur user;

    private String messageDest;
    private String messageObjet;
    private String messageTexte;
    private String messageDate;
    private String messageEmetteur;
    private View rootView;

    private static final String TAG_SUCCESS = "success";
    private JSONParser jsonParser = new JSONParser();

    private static final String url_connect = "http://locatme.alwaysdata.net/locateme/create_message.php";
    private static final String url_connect2 = "http://locatme.alwaysdata.net/locateme/recuperation_message.php";

    private ListView listView;

    public SendMessageFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_send_message,
                container, false);

        args = getArguments();


        final ImageButton submitMessageButton = (ImageButton) rootView
                .findViewById(R.id.imageSendButton);


        // On lie les bouton aux variables
        editmessage = (EditText) rootView.findViewById(R.id.editmessage);


        messages = new ArrayList<Message>();
        // Rcupration de l'objet dfinissant l'utilisateur connect
        user = (Utilisateur) getActivity().getIntent().getExtras().getParcelable("user");

        if (isNetworkConnected(getActivity().getApplicationContext())) {// faire le test de la connexion si oui---
            new Recuperation().execute();
            if (messages != null) {
                fillAdapter();
                try {
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    Log.e("Synchro", e.toString());
                }

            }

        } else {
            recuperationLocal();
        }


        // Si l'utilisateur est une personne
        if (Personne.class.isAssignableFrom(user.getClass())) {
            Personne personne = getActivity().getIntent().getExtras()
                    .getParcelable("user");


            txtemetteur = personne.getLogin();
            // Sinon c'est une nseigne
        } else {
            Enseigne enseigne = getActivity().getIntent().getExtras()
                    .getParcelable("user");
            txtemetteur = enseigne.getLogin();
        }
        submitMessageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new CreateMessage().execute();
                insererMessage(v);
                if (isNetworkConnected(getActivity().getApplicationContext())) {// faire le test de la connexion si oui---
                    new Recuperation().execute();
                } else {
                    recuperationLocal();
                    try {
                        adapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        Log.e("Synchro", e.toString());
                    }
                }
            }

        });

        return rootView;
    }

    private void fillAdapter() {
        Collections.sort(messages, Collections.reverseOrder());


        adapter = new MessageViewAdapter(getActivity(), R.id.listMessage, messages);

        setListView((ListView) rootView.findViewById(R.id.listMessage));


        getListView().setAdapter(adapter);
        getListView().setSelection(getListView().getCount());
    }

    private void recuperationLocal() {
        messageBDList = new MessageBD(getActivity());
        messageBDList.open();

        messages = messageBDList.RecupMessagesByReceiverAndSenders(user.getLogin(), args.getString("ami"));
        messages2 = messageBDList.RecupMessagesByReceiverAndSenders1(user.getLogin(), args.getString("ami"));

        if (messages2 != null) {
            if (messages != null) {
                messages.addAll(messages2);
            } else {
                messages = messages2;
            }

        }

        fillAdapter();
    }


    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected());
    }

    /**
     * insererMessage : Methode qui verifie les donnes des champs et fait appel
     * la methode d'insertion de MessageBD
     *
     * @param v : View
     */
    public void insererMessage(View v) {

        // cration et affectation de l'objet message
        messageBD = new MessageBD(this.getActivity());
        msg = new Message("aucun", getDate(), editmessage.getText().toString(), args.getString("ami"),
                user.getLogin());

        // Cration de l'objet utilisateurBD
        UtilisateurBD userBD = new UtilisateurBD(getActivity());
        userBD.open();


        // Verification de l'existance du login destinataire
        if (userBD.getPersonneByLogin(user.getLogin()) != null) {
            // Si le texte est vide
            if (args.getString("ami").equals("")) {
                Toast.makeText(getActivity(),
                        "you can't send an empty message", Toast.LENGTH_SHORT)
                        .show();
                // Si le texte n'est pas vide
            } else {
                messageBD.open();
                // si l'insertion s'est bien pass
                if (messageBD.insertMessage(msg) == -1) {
                    Toast.makeText(getActivity(), "Insert problem",
                            Toast.LENGTH_SHORT).show();

                } else {

                    editmessage.setText("");
                }
                messageBD.close();
            }

        } else {
            Toast.makeText(getActivity(), "User not found", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * getDate : Retourne un format de la date actuelle
     *
     * @return String de la date  un certain format
     */
    public String getDate() {
        Date currentDate = new Date();

        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "dd/MM/yy hh:mm:ss");
        String date = dateFormat.format(currentDate);

        return date;

    }


    class CreateMessage extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... strings) {


            editmessage = (EditText) getActivity().findViewById(R.id.editmessage);


            messageDest = args.getString("ami");
            messageObjet = "aucun";
            messageTexte = editmessage.getText().toString();
            messageDate = getDate();
            messageEmetteur = user.getLogin();

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("messageDest", messageDest));
            params.add(new BasicNameValuePair("messageObjet", messageObjet));
            params.add(new BasicNameValuePair("messageTexte", messageTexte));
            params.add(new BasicNameValuePair("messageDate", messageDate));
            params.add(new BasicNameValuePair("messageEmetteur", messageEmetteur));

            final JSONObject json = jsonParser.makeHttpRequest(url_connect, "POST", params);


            try {

                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {

                        }
                    });
                } else {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(SendMessageFragment.this.getActivity(), "Echec de l'envoi du message", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (JSONException e) {
                Log.e("Exception de json : ", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {

        }
    }


    public ListView getListView() {
        return listView;
    }

    public void setListView(ListView listView) {
        this.listView = listView;
    }


    class Recuperation extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... strings) {


            String destinataire = args.getString("ami");
            String emetteur = user.getLogin();


            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("destinataire", destinataire));
            params.add(new BasicNameValuePair("emetteur", emetteur));

            JSONObject json = jsonParser.makeHttpRequest(url_connect2,
                    "POST", params);

            Log.v("destinataire", destinataire);
            Log.v("emetteur", emetteur);

            try {
                JSONArray messagesJs = null;
                int success = json.getInt(TAG_SUCCESS);


                if (success == 1) {
                    Log.v("success ", "1");
                    messagesJs = json.getJSONArray("messages1");

                    messages.clear();

                    for (int i = 0; i < messagesJs.length(); i++) {
                        JSONObject c = messagesJs.getJSONObject(i);

                        // Storing each json item in variable
                        String ob = c.getString("objet");
                        String dat = c.getString("date");
                        String tx = c.getString("texte");
                        String dest = c.getString("destinataire");
                        String emet = c.getString("emetteur");

                        msg = new Message(ob, dat, tx, dest, emet);
                        messages.add(msg);


                    }
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            if (messages != null) {
                                fillAdapter();
                                try {
                                    adapter.notifyDataSetChanged();
                                } catch (Exception e) {
                                    Log.e("Synchro", e.toString());
                                }
                            }
                        }
                    });


                } else {

                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(getActivity(), " Aucun message ", Toast.LENGTH_LONG).show();
                        }
                    });


                }


            } catch (JSONException e) {

                Log.d("Exeception de json : ", e.toString());
            }
            return null;

        }

        @Override
        protected void onPostExecute(String s) {

        }
    }


}
